package com.apache.gateway.route;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @description: 限流策略
 * @author: Hou Dayu
 * @date: Created in 2020/2/25
 */
@Configuration
public class RequestRateLimiterConfig {

    /**
     * 获取请求服务名作为限流key
     */
    @Bean(name="idKeyResolver")
    @Primary
    public RemoteAddrResolver remoteAddrKeyResolver() {
        return new RemoteAddrResolver();
    }

    /**
     * 获取请求地址的uri作为限流key
     */
    @Bean(name="apiKeyResolver")
    public RequestPathResolver apiKeyResolver() {
        return new RequestPathResolver();
    }

    /**
     * 获取请求地址的IP限流作为限流key
     */
    @Bean(name="ipKeyResolver")
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }

    public class RequestPathResolver implements KeyResolver {//按请求URI限流
        @Override
        public Mono<String> resolve(ServerWebExchange exchange) {
            return Mono.just(exchange.getRequest().getPath().value());
        }
    }

    public class RemoteAddrResolver implements KeyResolver {//按服务限流
        @Override
        public Mono<String> resolve(ServerWebExchange exchange) {
            Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
            return Mono.just(route.getId());
        }
    }
}
